//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { Button, Checkbox, Input, List, message, Modal, Popover, Space } from "antd";
import type { TodoInfo, BasicTodoInfo } from "@/api/user_todo";
import { list_todo, create_todo, update_todo, remove_todo, clear_todo } from "@/api/user_todo";
import { request } from "@/utils/request";
import { get_session } from "@/api/user";
import { DeleteOutlined, MoreOutlined, PlusOutlined } from "@ant-design/icons";
import type * as NoticeType from '@/api/notice_type';
import { emit } from "@tauri-apps/api/event";
import { EditTextArea } from "@/components/EditCell/EditTextArea";

export interface UserTodoListProps {
    showClock: boolean;
}

const UserTodoList = (props: UserTodoListProps) => {
    const [newTitle, setNewTitle] = useState("");
    const [todoList, setTodoList] = useState<TodoInfo[]>([]);
    const [removeInfo, setRemoveInfo] = useState<TodoInfo | null>(null);
    const [showClearModal, setShowClearModal] = useState(false);

    const loadTodoList = async () => {
        const sessionId = await get_session();
        const res = await request(list_todo({ session_id: sessionId }));
        setTodoList(res.todo_list);
    };

    const createTodo = async () => {
        if (newTitle == "") {
            return;
        }
        const sessionId = await get_session();
        await request(create_todo({
            session_id: sessionId,
            basic_info: {
                title: newTitle,
                title_color: "black",
                done: false,
            },
        }));
        message.info("创建成功");
        setNewTitle("");
        await loadTodoList();
        const notice: NoticeType.AllNotice = {
            ClientNotice: {
                UserTodoChangeNotice: {},
            }
        };
        emit("notice", notice);
    };

    const updateTodo = async (todoId: string, basicInfo: BasicTodoInfo) => {
        const sessionId = await get_session();
        await request(update_todo({
            session_id: sessionId,
            todo_id: todoId,
            basic_info: basicInfo,
        }));
        const tmpList = todoList.slice();
        const index = tmpList.findIndex(item => item.todo_id == todoId);
        if (index != -1) {
            tmpList[index].basic_info = basicInfo;
            setTodoList(tmpList);
        }

        const notice: NoticeType.AllNotice = {
            ClientNotice: {
                UserTodoChangeNotice: {},
            }
        };
        emit("notice", notice);
    };

    const removeTodo = async () => {
        if (removeInfo == null) {
            return;
        }
        const sessionId = await get_session();
        await request(remove_todo({
            session_id: sessionId,
            todo_id: removeInfo.todo_id,
        }));
        message.info("删除成功");
        setRemoveInfo(null);
        await loadTodoList();

        const notice: NoticeType.AllNotice = {
            ClientNotice: {
                UserTodoChangeNotice: {},
            }
        };
        emit("notice", notice);
    }

    const clearTodo = async () => {
        const sessionId = await get_session();
        await request(clear_todo({
            session_id: sessionId,
        }));
        message.info("清空成功");
        setShowClearModal(false);
        await loadTodoList();

        const notice: NoticeType.AllNotice = {
            ClientNotice: {
                UserTodoChangeNotice: {},
            }
        };
        emit("notice", notice);
    };

    useEffect(() => {
        loadTodoList();
    }, []);

    return (
        <div>
            <Space>
                <Input style={{ width: "280px", marginLeft: "10px" }} placeholder="请输入待办事项" size="large" value={newTitle} allowClear
                    onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setNewTitle(e.target.value.trim());
                    }} />
                <Button type="primary" icon={<PlusOutlined />} disabled={newTitle == ""} onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    createTodo();
                }}>创建</Button>
                <Popover placement="bottom" trigger="click" content={
                    <Space direction="vertical">
                        <Button type="link" danger disabled={todoList.length == 0}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                setShowClearModal(true);
                            }}>清空</Button>
                    </Space>
                }>
                    <MoreOutlined />
                </Popover>
            </Space>
            <List rowKey="todo_id" dataSource={todoList} pagination={false} style={{ height: props.showClock ? "calc(100vh - 170px" : "calc(100vh - 130px)", overflowY: "scroll", padding: "10px 10px" }}
                renderItem={todo => (
                    <List.Item style={{ borderBottom: "1px solid #e4e4e8" }}
                        extra={
                            <Space>
                                {todo.basic_info.done == false && (
                                    <Popover placement="bottom" trigger="click" content={
                                        <Space>
                                            {["black", "red", "green"].map(color => (
                                                <div key={color} style={{ width: "16px", height: "16px", backgroundColor: color, cursor: "pointer", borderRadius: "8px" }}
                                                    onClick={e => {
                                                        e.stopPropagation();
                                                        e.preventDefault();
                                                        updateTodo(todo.todo_id, {
                                                            title: todo.basic_info.title,
                                                            title_color: color,
                                                            done: todo.basic_info.done,
                                                        });
                                                    }} />
                                            ))}
                                        </Space>
                                    }>
                                        <div style={{ width: "16px", height: "16px", backgroundColor: todo.basic_info.title_color, cursor: "pointer", borderRadius: "8px" }} />
                                    </Popover>
                                )}
                                {todo.basic_info.done == true && (
                                    <div style={{ width: "16px", height: "16px", backgroundColor: "grey", borderRadius: "8px" }} />
                                )}
                                <Button type="link" icon={<DeleteOutlined />} danger onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setRemoveInfo(todo);
                                }} />
                            </Space>
                        }>
                        <Space size="large">
                            <Checkbox checked={todo.basic_info.done} onChange={e => {
                                e.stopPropagation();
                                updateTodo(todo.todo_id, {
                                    title: todo.basic_info.title,
                                    title_color: todo.basic_info.title_color,
                                    done: e.target.checked,
                                });
                            }} />
                            <div style={{ width: "260px", fontWeight: 600, color: todo.basic_info.done ? "#aaa" : todo.basic_info.title_color }}>
                                <EditTextArea editable={!todo.basic_info.done} content={todo.basic_info.title} showEditIcon
                                    editWidth="100%" fontSize="14px"
                                    textDecoration={todo.basic_info.done ? "line-through" : "none"}
                                    onChange={async value => {
                                        if (value.trim() == "") {
                                            return false;
                                        }
                                        try {
                                            await updateTodo(todo.todo_id, {
                                                title: value.trim(),
                                                title_color: todo.basic_info.title_color,
                                                done: todo.basic_info.done,
                                            });
                                            return true;
                                        } catch (e) {
                                            return false;
                                        }
                                    }} />
                            </div>
                        </Space>
                    </List.Item>
                )} />
            {removeInfo != null && (
                <Modal open title="删除待办" mask={false} width={300}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeTodo();
                    }}>
                    是否删除待办&nbsp;{removeInfo.basic_info.title}&nbsp;?
                </Modal>
            )}
            {showClearModal == true && (
                <Modal open title="清空待办" mask={false} width={300}
                    okText="清空" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowClearModal(false);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        clearTodo();
                    }}>
                    是否清空所有待办记录？
                </Modal>
            )}
        </div>
    );
};

export default UserTodoList;